/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ManGuia.java
 *
 * Created on 01/03/2011, 04:36:31 PM
 */

package com.catosist.run.application.venta.guia;
import com.catosist.run.application.Util.ButtonTabComponent;
import com.catosist.run.business.gestorComprobanteDetalle.GestorComprobanteDetalle;
import com.catosist.run.business.gestorguia.GestorGuia;
import com.catosist.run.services.ComprobanteDetalleDTO;
import com.catosist.run.services.GuiaDTO;
import java.awt.Dialog;
import java.util.Iterator;
import javax.swing.table.DefaultTableModel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author igorov
 */
public class ManGuia extends javax.swing.JDialog {

    /** Creates new form ManGuia */
    public ManGuia(java.awt.Frame parent, boolean modal, int comprobanteId, List<ComprobanteDetalleDTO> lista_comprobantes, GestorComprobanteDetalle gestorComprobanteDetalle) {
        super(parent, modal);
        initComponents();
        this.gestorComprobanteDetalle = gestorComprobanteDetalle;
        this.comprobanteId = comprobanteId;
        iniciar();
        iniciarListasConmprobantes(lista_comprobantes);
        this.lblTitle.setText("Guias de Remision para la factura: " + this.comprobanteId);
        
        refresh();
    }

    public ManGuia(Dialog owner, boolean modal, int comprobanteId, List<ComprobanteDetalleDTO> lista_comprobantes, GestorComprobanteDetalle gestorComprobanteDetalle) {
        super(owner, modal);
        initComponents();
        this.gestorComprobanteDetalle = gestorComprobanteDetalle;
        this.comprobanteId = comprobanteId;
        iniciar();
        iniciarListasConmprobantes(lista_comprobantes);
        this.lblTitle.setText("Guias de Remision para la factura: " + this.comprobanteId);

        refresh();
    }



    public void iniciar(){
        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
        gestorGuia = (GestorGuia) ctx.getBean("gestorGuia");
        lista_comprobantes_con_guias = new LinkedList<ComprobanteDetalleDTO>();
        lista_comprobantes_sin_guias = new LinkedList<ComprobanteDetalleDTO>();
    }

    public void refresh(){
        DefaultTableModel model = new DefaultTableModel();
        model.addColumn("ID");
        model.addColumn("Guia No");
        model.addColumn("Descripcion");
        model.addColumn("Remitente");
        model.addColumn("Destinatario");

        Set<Integer> id_guias = new HashSet<Integer>();
        for (Iterator<ComprobanteDetalleDTO> it = lista_comprobantes_con_guias.iterator(); it.hasNext();) {
            ComprobanteDetalleDTO comprobanteDetalleDTO = it.next();
            id_guias.add(comprobanteDetalleDTO.getGuiaId());
        }
        for (Iterator<ComprobanteDetalleDTO> it = lista_comprobantes_sin_guias.iterator(); it.hasNext();) {
            ComprobanteDetalleDTO comprobanteDetalleDTO = it.next();
            id_guias.add(comprobanteDetalleDTO.getGuiaId());
        }

        Iterator ite = id_guias.iterator();

        while (ite.hasNext()){
            int guia_id = (Integer) ite.next();
            if(guia_id != 0){
                GuiaDTO guiaDTO = (GuiaDTO) gestorGuia.getById(guia_id);
                model.addRow(guiaDTO.toArray());
            }
//            System.out.println("Guia: " + ite.next());
        }
//        while (ite.hasNext()){
//
//            int guia_id = (Integer) ite.next();
//
//            GuiaDTO guiaDTO = (GuiaDTO) gestorGuia.getById(guia_id);
//            model.addRow(guiaDTO.toArray());
//
////            System.out.println("Guia: " + ite.next());
//        }
            
//        List<GuiaDTO> guiaDTOs = gestorGuia.getByComprobanteId(comprobanteId);
//        for (Iterator<GuiaDTO> it = guiaDTOs.iterator(); it.hasNext();) {
//            GuiaDTO comprobanteDTO = it.next();
//            model.addRow(comprobanteDTO.toArray());
//        }

        this.jTable1.setModel(model);
    }

    public void agregaPestanha(JPanel panel, String titulo) {
        this.tabWork.add(titulo, panel);
        this.tabWork.setSelectedIndex(this.tabWork.getTabCount() - 1);
        ButtonTabComponent pestana = new ButtonTabComponent("nano", this.tabWork);
        this.tabWork.setTabComponentAt(this.tabWork.getTabCount() - 1, pestana);
    }

    private void iniciarListasConmprobantes(List<ComprobanteDetalleDTO> comprobanteDetalleDTOs){
        
        for (Iterator<ComprobanteDetalleDTO> it = comprobanteDetalleDTOs.iterator(); it.hasNext();) {
            ComprobanteDetalleDTO comprobanteDetalleDTO = it.next();
            if (comprobanteDetalleDTO.getGuiaId() == 0)
                lista_comprobantes_sin_guias.add(comprobanteDetalleDTO);
            else lista_comprobantes_con_guias.add(comprobanteDetalleDTO);

        }
    }

    public List<ComprobanteDetalleDTO> getLista_comprobantes_con_guias() {
        return lista_comprobantes_con_guias;
    }

    public void setLista_comprobantes_con_guias(List<ComprobanteDetalleDTO> lista_comprobantes_con_guias) {
        this.lista_comprobantes_con_guias = lista_comprobantes_con_guias;
    }

    public List<ComprobanteDetalleDTO> getLista_comprobantes_sin_guias() {
        return lista_comprobantes_sin_guias;
    }

    public void setLista_comprobantes_sin_guias(List<ComprobanteDetalleDTO> lista_comprobantes_sin_guias) {
        this.lista_comprobantes_sin_guias = lista_comprobantes_sin_guias;
    }

    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        lblTitle = new javax.swing.JLabel();
        tabWork = new javax.swing.JTabbedPane();
        btnNuevo = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnDetalles = new javax.swing.JButton();
        btnCerrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.catosist.run.application.desktopapplication.DesktopApplication.class).getContext().getResourceMap(ManGuia.class);
        lblTitle.setText(resourceMap.getString("lblTitle.text")); // NOI18N
        lblTitle.setName("lblTitle"); // NOI18N

        tabWork.setName("tabWork"); // NOI18N

        btnNuevo.setText(resourceMap.getString("btnNuevo.text")); // NOI18N
        btnNuevo.setName("btnNuevo"); // NOI18N
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnEliminar.setText(resourceMap.getString("btnEliminar.text")); // NOI18N
        btnEliminar.setName("btnEliminar"); // NOI18N
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnDetalles.setText(resourceMap.getString("btnDetalles.text")); // NOI18N
        btnDetalles.setName("btnDetalles"); // NOI18N
        btnDetalles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetallesActionPerformed(evt);
            }
        });

        btnCerrar.setText(resourceMap.getString("btnCerrar.text")); // NOI18N
        btnCerrar.setName("btnCerrar"); // NOI18N
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(btnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnEliminar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnDetalles)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCerrar, 0, 0, Short.MAX_VALUE)
                                .addGap(12, 12, 12))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 465, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addComponent(tabWork, javax.swing.GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE))
                    .addComponent(lblTitle))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitle)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(tabWork, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 627, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 596, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnNuevo)
                            .addComponent(btnEliminar)
                            .addComponent(btnDetalles)
                            .addComponent(btnCerrar))))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnDetallesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetallesActionPerformed
        // TODO add your handling code here:
        try {
            int i = Integer.parseInt(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0).toString());
            GuiaDetalles guiaDetalles = new GuiaDetalles(this, gestorGuia, i, gestorComprobanteDetalle);
            agregaPestanha(guiaDetalles.getPanel(), "Guias de remision");
            refresh();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar una factura existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }

//            facturaDetalles.setVisible(true);
        
    }//GEN-LAST:event_btnDetallesActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        // TODO add your handling code here:
        GuiaDetalles guiaDetalles = new GuiaDetalles(this, gestorGuia, 0, gestorComprobanteDetalle);
        agregaPestanha(guiaDetalles.getPanel(), "Guias");
        refresh();
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_btnCerrarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        try {
            int result = JOptionPane.showConfirmDialog(this, "Realmente desea eliminar el registro?","Eliminar Guia de Remision", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                int i = Integer.parseInt(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0).toString());

                for (Iterator<ComprobanteDetalleDTO> it = lista_comprobantes_con_guias.iterator(); it.hasNext();) {
                    ComprobanteDetalleDTO comprobanteDetalleDTO = it.next();
                    if (comprobanteDetalleDTO.getGuiaId() == i) {
                        comprobanteDetalleDTO.setGuiaId(-1);
                        lista_comprobantes_sin_guias.add(comprobanteDetalleDTO);
                        gestorComprobanteDetalle.saveOrUpdate(comprobanteDetalleDTO, comprobanteId);
                        lista_comprobantes_con_guias.remove(comprobanteDetalleDTO);
                    }
                }
                gestorGuia.deleteById(i);
                refresh();
            }
        } catch (Exception e) {
        }

    }//GEN-LAST:event_btnEliminarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
//                ManGuia dialog = new ManGuia(new javax.swing.JFrame(), true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCerrar;
    private javax.swing.JButton btnDetalles;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JTabbedPane tabWork;
    // End of variables declaration//GEN-END:variables

    private int comprobanteId;
    private ApplicationContext ctx;
    private GestorGuia gestorGuia;
    private List<ComprobanteDetalleDTO> lista_comprobantes_con_guias;
    private List<ComprobanteDetalleDTO> lista_comprobantes_sin_guias;

    private GestorComprobanteDetalle gestorComprobanteDetalle;

}
